package com.atxuwei.yygh.msm.controller;

import com.atxuwei.yygh.common.result.Result;
import com.atxuwei.yygh.msm.service.MsmService;
import com.atxuwei.yygh.msm.utils.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/msm")
public class MsmApiController {
    @Autowired
    private MsmService msmService;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    //发送手机验证码
    @GetMapping("send/{phone}")
    public Result sendCode(@PathVariable String phone){
        //从redis中获取存入验证码
        String code = redisTemplate.opsForValue().get(phone);
        //判断验证码是否存在
        if(!StringUtils.isEmpty(code)){
            return Result.ok();
        }
        //为空就生成验证码
        code= RandomUtil.getSixBitRandom();
        //调用service方法整合阿里云短信服务发送短信，
        //TODO boolean isSend=msmService.send(phone,code);
        //发送成功保存入redis中
        if(true){
            //阿里云短信服务未通过，定义固定验证码code:123456
            redisTemplate.opsForValue().set(phone,"123456",5, TimeUnit.MINUTES);
            return Result.ok();
        }else {
            return Result.fail().message("发送短信失败！");
        }
    }
}
